'''
Created on 11-Nov-2012

@author: kshitiz
'''
import threading
from fetchemApp.models import *
from fetchemApp import EmailLib
import time, datetime

from django.db import transaction

@transaction.commit_manually
def flush_transaction():
    """
    Flush the current transaction so we don't read stale data

    Use in long running processes to make sure fresh data is read from
    the database.  This is a problem with MySQL and the default
    transaction mode.  You can fix it by setting
    "transaction-isolation = READ-COMMITTED" in my.cnf or by calling
    this function at the appropriate moment
    """
    transaction.commit()
    
#Can be called directly
#Returns True if the fetching has started.
#Return False if it is already being fetched.
def fetchMain(A):
    
    ListOfThreads = threading.enumerate()
    #print str(len(ListOfThreads)) + ' is the number of threads!'
    for i in ListOfThreads:
        if i.name == "FetchingThread-"+ str(A.id):
            #It is already being fetched. 
            return False
    T = threading.Thread(name=('FetchingThread-'+str(A.id)), target=EmailLib.fetch, kwargs={'assign_object': A})
    T.start()
    return True

#This is the function to call on starting up Django.
def theFetchLooper():
    while(True):
        print 'FetchLooper: Fetching again.'
        flush_transaction()
        print 'Model Cache flushed'
        now = datetime.datetime.now()
        AssnList = Assignment.objects.filter(EndDateTime__gte=now).exclude(StartDateTime__gte=now)
        for i in AssnList:
            fetchMain(i)
        print 'FetchLooper: Going to sleep'
        time.sleep(900)
    